/**
 * 自定义公共函数
 */
export default {
	/**
	 * 添加商品到购物车
	 * let addCartRes = vk.myfn.cart.add({ goodsInfo, selectShop });
	 */
	add(obj) {
		let vk = uni.vk;
		let { goodsInfo = {}, selectShop = {} } = obj;
		let res = { code: 0, msg: "" };
		let goods = {
			sku_id: selectShop._id, // 主要参数 - skuID
			buy_num: Number(selectShop.buy_num), // 主要参数 - 购买数量
			sku_name: selectShop.sku_name, // 展示参数 - sku名称
			image: selectShop.image, // 展示参数 - sku图片
			price: Number(selectShop.price), // 展示参数 - sku价格
			stock: Number(selectShop.stock), // 展示参数 - sku库存
			goods_id: goodsInfo._id, // 展示参数 - 商品ID
			goods_name: goodsInfo.name, // 展示参数 - 商品名称
			goods_type: goodsInfo.type, // 展示参数 - 商品类型
			cart_rule: goodsInfo.cart_rule || {}, // 展示参数 - 购物车规则
			action_checked: true, // 辅助参数 - 购物车是否选中
		};

		if (!goods.goods_id || !goods.sku_id) {
			let errMsg = "商品信息错误";
			console.error(errMsg);
			return { code: -1, msg: errMsg };;
		}
		let list = vk.getVuex('$cart.list');
		let isNotExistent = true;
		for (let i in list) {
			if (list[i].goods_id === goods.goods_id && list[i].sku_id === goods.sku_id) {
				list[i].buy_num += goods.buy_num;
				list[i].stock = goods.stock;
				if (list[i].buy_num > goods.stock) {
					list[i].buy_num = goods.stock;
				}
				isNotExistent = false;
				break;
			}
		}
		if (isNotExistent) {
			// 如果不存在，代表新增商品，记录新增时间
			goods.add_time = Date.now();
			list.push(goods);
		}
		vk.vuex.dispatch('$cart/setCart', list);
		let nameStr = `${goods.goods_name} ${goods.sku_name}`;
		if (nameStr.length > 20) {
			nameStr = nameStr.substring(0, 20) + "...";
		}
		res.msg = `已将（${nameStr}）加入购物车`;
		let count = String(vk.vuex.getters('$cart/getTotal'));
		uni.setTabBarBadge({
			index: 2,
			text: count
		});
		return res;
	}
};
